<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="70%"
    :destroy-on-close="true"
    :close-on-click-modal="false"
    class="vuln-detail-dialog"
    @closed="handleClosed"
  >
    <div v-loading="loading">
      <el-descriptions
        border
        class="vuln-descriptions"
        :column="2"
        size="large"
      >
        <el-descriptions-item label="漏洞ID" label-align="left">{{
          detail.id
        }}</el-descriptions-item>
        <el-descriptions-item label="漏洞来源" label-align="left">{{
          detail.source
        }}</el-descriptions-item>
        <el-descriptions-item label="产品类型" label-align="left">{{
          detail.product_type
        }}</el-descriptions-item>
        <el-descriptions-item label="数据源" label-align="left">{{
          detail.is_standard === 1 ? "标准库" : "预备库"
        }}</el-descriptions-item>
        <el-descriptions-item label="CVE编号" label-align="left">
          <!-- <a
            :href="`https://cve.mitre.org/cgi-bin/cvename.cgi?name=${detail.cve_id}`"
            target="_blank"
            class="link-text"
            ></a
          > -->
          {{ detail.cve_id }}
        </el-descriptions-item>
        <el-descriptions-item label="CNVD编号" label-align="left">{{
          detail.cnvd_id || "暂无"
        }}</el-descriptions-item>
        <el-descriptions-item label="危害等级" label-align="left">
          <el-tag :type="getTagType(detail.level)">{{ detail.level }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="安全评分" label-align="left">{{
          detail.score
        }}</el-descriptions-item>
        <el-descriptions-item label="CVSS" label-align="left" :span="2">
          <el-tag type="info" effect="plain">{{ detail.cvss }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="CWE编号" label-align="left">
          <!-- <a
            :href="`https://cwe.mitre.org/data/definitions/${detail.cwe}.html`"
            target="_blank"
            class="link-text"
            >{{  }}</a
          > -->
          {{ detail.cwe }}
        </el-descriptions-item>
        <el-descriptions-item label="CWE描述" label-align="left">{{
          detail.cwe_description
        }}</el-descriptions-item>
        <el-descriptions-item label="漏洞类型" label-align="left">{{
          detail.vuln_type || "未知"
        }}</el-descriptions-item>
        <el-descriptions-item label="厂商" label-align="left">{{
          detail.vendor || "未知"
        }}</el-descriptions-item>
        <el-descriptions-item label="发布时间" label-align="left">{{
          detail.publish_time
        }}</el-descriptions-item>
        <el-descriptions-item label="更新时间" label-align="left">{{
          detail.update_time || "暂无"
        }}</el-descriptions-item>
        <el-descriptions-item label="影响产品" label-align="left" :span="2">
          <div
            v-for="(product, index) in detail.product_list"
            :key="index"
            class="product-item"
          >
          {{ product }}
            <!-- <a :href="ref" target="_blank" class="link-text">{{  }}</a> -->
          </div>
        </el-descriptions-item>
      </el-descriptions>

      <div class="section-title">漏洞描述</div>
      <div class="section-content">{{ detail.description }}</div>

      <el-collapse v-model="activeCollapseNames" class="poc-collapse">
        <el-collapse-item name="pocExp">
          <template #title>
            <div class="section-title">poc/exp文件信息</div>
          </template>
          <div class="section-content section-panel">
            <div
              v-for="(ref, index) in detail.poc_list"
              :key="index"
              class="code-item"
            >
              <div class="code-header">
                <span class="code-filename"
                  >poc_script_{{ ref.id }}.{{ ref.type }}</span
                >
                <el-button
                  size="small"
                  type="primary"
                  @click="handleDownloadPyFile(ref, index)"
                  class="download-btn"
                >
                  <Download />
                  下载
                </el-button>
              </div>
              <pre><code v-html="renderedSolution(ref.poc_exp)"></code></pre>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>

      <div class="section-title">漏洞危害</div>
      <div class="section-content">
        {{ detail.vuln_danger || "暂无危害描述" }}
      </div>

      <div class="section-title">漏洞利用</div>
      <div class="section-content">{{ detail.vuln_use || "暂无利用信息" }}</div>

      <div class="section-title">补丁信息</div>
      <div class="section-content">
        {{ detail.vuln_patch || "暂无补丁信息" }}
      </div>

      <div class="section-title">参考链接</div>
      <div class="section-content">
        <template v-if="detail?.vuln_references?.length > 0">
          <div
            v-for="(ref, index) in detail?.vuln_references"
            :key="index"
            class="reference-item"
          >
            <!-- <a :href="ref" target="_blank" class="link-text"></a> -->
             {{ ref }}
          </div>
        </template>
        <template v-else> 暂无参考链接 </template>
      </div>

      <div
        v-if="detail.poc_exps && detail.poc_exps.length > 0"
        class="section-title"
      >
        POC/EXP文件
      </div>
      <div
        v-if="detail.poc_exps && detail.poc_exps.length > 0"
        class="section-content"
      >
        <el-button
          v-for="(file, index) in detail.poc_exps"
          :key="index"
          :type="file.type === 'poc' ? 'primary' : 'danger'"
          size="small"
          @click="handleDownloadFile(file)"
        >
          下载{{ file.type === "poc" ? "POC" : "EXP" }}
        </el-button>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" plain @click="handleGenerateReport"
          >生成报告</el-button
        >
        <el-button @click="visible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { ElMessage, ElCollapse, ElCollapseItem, ElButton } from "element-plus";
import { Download } from "@element-plus/icons-vue";
import { getVulnMatchDetail } from "@/api/vulnMatch";
import { downloadFileFromResponse } from "@/utils/fileOpt";
// 接收参数
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  vulnData: {
    type: Object,
    default: () => ({}),
  },
});

// 发出事件
const emit = defineEmits(["update:modelValue", "closed"]);
const renderedSolution = (html) => {
  let res = '';
  if(html){
    res = html
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/\\n/g, '<br>');        
  } 
  return res;
}
// 显示状态
const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit("update:modelValue", val),
});

// 标题
const title = computed(() => {
  const cveId = detail.value.cve_id || "";
  const vendor = detail.value.vendor || "";
  return `漏洞详情 - ${cveId} ${vendor}`;
});

// 组件状态
const loading = ref(false);
const detail = computed(() => props.vulnData || {});
const activeCollapseNames = ref([]);

// 处理PY脚本下载
const handleDownloadPyFile = (ref, index) => {
  if (!ref || !ref.poc_exp) {
    ElMessage.warning("脚本内容不存在");
    return;
  }

  // 创建Blob对象
  const blob = new Blob([ref.poc_exp], { type: "text/plain" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `poc_script_${index + 1}.py`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
  ElMessage.success("文件下载成功");
};

// 处理下载文件
const handleDownloadFile = (file) => {
  if (!file || !file.url) {
    ElMessage.warning("文件不存在");
    return;
  }

  ElMessage.success("文件下载中...");
  // 这里需要实际的下载逻辑
};

// 生成漏洞报告
const handleGenerateReport = async () => {
  try {
    ElMessage.info("正在生成报告...");

    const data = {
      id_list: [detail.value.id],
    };

    // 调用生成报告接口
    const res = await getVulnMatchDetail(data);

    // 下载文件
    downloadFileFromResponse(res);

    ElMessage.success("报告生成成功");
  } catch (error) {
    console.error("生成报告失败:", error);
    ElMessage.error("报告生成失败，请稍后重试");
  }
};

// 获取标签类型
const getTagType = (level) => {
  const typeMap = {
    高危: "danger",
    中危: "warning",
    低危: "info",
  };
  return typeMap[level] || "";
};

// 关闭对话框
const handleClosed = () => {
  emit("closed");
};
</script>

<style lang="scss" scoped>
.vuln-detail-dialog {
  :deep(.el-dialog__body) {
    padding: 20px;
  }
}

.vuln-descriptions {
  margin-bottom: 20px;

  :deep(.el-descriptions__label) {
    width: 120px;
    font-weight: bold;
  }
}

.link-text {
  color: var(--el-color-primary);
  text-decoration: none;

  &:hover {
    text-decoration: underline;
  }
}

.pocCode {
  display: -webkit-box; /* 使用 flexbox 布局 */
  -webkit-box-orient: vertical; /* 垂直排列 */
  -webkit-line-clamp: 3; /* 限制为 3 行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 使用省略号表示被隐藏的文本 */
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0 10px;
  padding-left: 10px;
  border-left: 4px solid var(--el-color-primary);
}

.section-content {
  background-color: var(--bg-color);
  padding: 15px;
  border-radius: 4px;
  white-space: pre-line;
  line-height: 1.6;
}

.product-item {
  margin-bottom: 8px;
}

.product-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.reference-item {
  margin-bottom: 8px;

  &:last-child {
    margin-bottom: 0;
  }
}

.code-item {
  margin-bottom: 20px;
  border: 1px solid var(--border-color); //#e5e7eb;
  border-radius: 4px;
  overflow: hidden;
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background-color: var(--desc-bg); //#f5f7fa;
  border-bottom: 1px solid var(--border-color); //#e5e7eb;
}

.code-filename {
  font-weight: 500;
  color: #409eff;
}

.download-btn {
  padding: 4px 8px;
}

.code-item pre {
  margin: 0;
  padding: 12px;
  background-color: var(--card-bg); // #fafafa;
  overflow-x: auto;
}
</style>
